﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
//using System.Windows.Forms;
using ESOL.Common.Entity;
using ESOL.Business.Sec;
using ESOL.Business.Mst;
using ESOL.Common;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraBars;
using DevExpress.XtraNavBar;
using System.Threading;

namespace ESOL.WinUI
{
    public partial class frmMain : BaseForm.frmBaseMdiParentForm
    {
        #region Variable
        public frmLogin LoginForm { get; set; }
        private delegate Form dlLoadForm(object obj);
        private Form tempForm;
        #endregion

        #region Constructor
        public frmMain()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void SetStatusBar()
        {
            if (CommonParameter.CurrentUser == null)
            {
                Application.Exit();
            }
            SecUserEntity user = (SecUserEntity)CommonParameter.CurrentUser;
            if (user != null)
            {
                ssLoginUser.Text = "登录用户：" + user.ChineseName;
            }
            else
            {
                ssLoginUser.Text = "登录用户：Null";
            }
            ssLoginTime.Text = "登陆时间：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }

        private Form LoadFormForMenu(object obj)
        {
            Form form = null;
            SecMenuEntity menu = (SecMenuEntity)obj;
            //加载Form窗口所在的程序集
            Assembly assDLL = Assembly.LoadFrom(Application.StartupPath + "\\" + menu.ExeFile);
            if (assDLL == null)
            {
                throw new Exception("找不到文件" + menu.ExeFile + "\n请更新程序");
            }
            //根据窗体名称生成对应的窗体
            form = (Form)assDLL.CreateInstance(menu.FormName);
            if (form == null)
            {
                throw new Exception("在文件" + menu.ExeFile + "中找不到类文件" + menu.FormName + "\n请更新程序");
            }
            form.Tag = menu.MenuId;
            form.Text = menu.MenuName;
            return form;
        }

        //private void CrossThreadFlush(object menu)
        //{            
        //    dlLoadForm dl = LoadFormForMenu;
        //    IAsyncResult asyncResult = this.BeginInvoke(dl,menu);
        //    //IAsyncResult asyncResult = dl.BeginInvoke(menu, null, null);
        //    while (!asyncResult.IsCompleted)
        //    {
        //        Thread.Sleep(100);
        //    }
        //    // 由于异步调用已经完成，因此， EndInvoke会立刻返回结果
        //    Form result = (Form)this.EndInvoke(asyncResult);
        //    result.MdiParent = this;
        //    result.Show();
        //}

        private delegate void dlRunMethod();//定义一个委托，用于执行方法
        public void InstallMenus(NavBarGroup ownerMenu, SecMenuEntity menu)
        {
            string strMenuID = menu == null ? "" : menu.MenuId;
            //根据用户和父菜单来查询对应的子菜单，可换成你的查询代码
            List<SecMenuEntity> list = null;
            list = SecMenuBs.GetMenusByParentID(strMenuID, Common.CommonParameter.CurrentUser.PersonId);
            if (list == null)
            {
                return;
            }
            //初始调用的时候，清空MenuStrip的所有内容
            if (ownerMenu == null)
            {
                navMenu.Groups.Clear();
            }
            if (list.Count == 0 && ownerMenu == null)
            {
                return;
            }
            foreach (SecMenuEntity entity in list)
            {
                List<SecMenuEntity> listChildren = new List<SecMenuEntity>();
                listChildren = SecMenuBs.GetMenusByParentID(entity.MenuId, Common.CommonParameter.CurrentUser.PersonId);
                NavBarGroup navBarGroup;
                NavBarItem navBarItem;
                if (listChildren.Count > 0)
                {
                    navBarGroup = new NavBarGroup();
                    navBarGroup.Caption = entity.MenuName;
                    navBarGroup.Tag = entity.MenuId;
                    navMenu.Groups.Add(navBarGroup);
                    InstallMenus(navBarGroup, entity);
                }
                else
                {
                    navBarItem = new NavBarItem();
                    navBarItem.Caption = entity.MenuName;
                    navBarItem.Tag = entity;
                    ownerMenu.ItemLinks.Add(navBarItem);
                    navBarItem.LinkClicked += new NavBarLinkEventHandler(navBarItem_LinkClicked);
                }
            }
        }

        void navBarItem_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            SecMenuEntity menu = (SecMenuEntity)((NavBarItem)sender).Tag;

            foreach (Form frmOpen in this.MdiChildren)
            {
                if (frmOpen.Tag!=null&&frmOpen.Tag.Equals(menu.MenuId))
                {
                    frmOpen.BringToFront();
                    return;
                }
            }

            //后台线程获取菜单窗体，前台显示进度条
            Form frm=LoadFormForMenu(menu);
            frm.MdiParent = this;
            frm.Show();
            //Thread thread = new Thread(new ParameterizedThreadStart(CrossThreadFlush));
            //thread.IsBackground = true;
            //thread.Start(menu);
        }
        #endregion

        #region Event
        private void frmMain_Load(object sender, EventArgs e)
        {
            SetStatusBar();
            NavBarGroup ownerMenu = null;
            SecMenuEntity menu = null;
            InstallMenus(ownerMenu, menu);
            frmDesktop desktop = new frmDesktop();
            desktop.MdiParent = this;
            desktop.Show();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (LoginForm != null)
            {
                LoginForm.Close();
            }
            base.OnClosing(e);
            if (LoginForm != null)
            {
                LoginForm.Dispose();
            }
        }

        private void tsmCloseCurrentWindow_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                this.ActiveMdiChild.Close();
            }
        }

        private void CloseAllChildForm()
        {
            if (this.MdiChildren.Length > 0)
            {
                for (int i = MdiChildren.Length - 1; i >= 0; i--)
                {
                    MdiChildren[i].Close();
                }
            }
        }

        private void tsmCloseAllWindows_ItemClick(object sender, ItemClickEventArgs e)
        {
            CloseAllChildForm();
        }

        private void tsmChangePassword_ItemClick(object sender, ItemClickEventArgs e)
        {
            Sec.frmChangePassword frm = new Sec.frmChangePassword();
            frm.ShowDialog();
        }

        private void tsmReLogin_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmLogin frm = new frmLogin();
            frm.ShowInTaskbar = false;
            frm.IsStartForm = false;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                LoginForm.Hide();

                CloseAllChildForm();
                frmMain_Load(null, null);
            }
        }

        private void tsmCalc_ItemClick(object sender, ItemClickEventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");//计算器
        }

        private void tsmNotepad_ItemClick(object sender, ItemClickEventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe");//记事本
        }

        private void tsmExcel_ItemClick(object sender, ItemClickEventArgs e)
        {
            System.Diagnostics.Process.Start("excel.exe");//Excel
        }

        private void tsmWord_ItemClick(object sender, ItemClickEventArgs e)
        {
            System.Diagnostics.Process.Start("winword.exe");//Word
        }

        private void navMenu_GroupExpanded(object sender, NavBarGroupEventArgs e)
        {
            NavBarGroup group = e.Group;
            if (group.Tag == null)
            {
                return;
            }
            SecMenuEntity menu = SecMenuBs.GetMenuByID(group.Tag.ToString());
            if (menu == null)
            {
                return;
            }
            List<SecMenuEntity> menus = SecMenuBs.GetMenusByParentID(menu.MenuId);
            if (menus.Count == 0)
            {
                return;
            }
            foreach(SecMenuEntity entity in menus)
            {
                if (entity.MasterFlag == 1)
                {
                    foreach (Form frmOpen in this.MdiChildren)
                    {
                        if (frmOpen.Tag != null && frmOpen.Tag.Equals(entity.MenuId))
                        {
                            frmOpen.BringToFront();
                            return;
                        }
                    }
                    //后台线程获取菜单窗体，前台显示进度条
                    Form frm = LoadFormForMenu(entity);
                    frm.MdiParent = this;
                    frm.Show();
                    break;
                }
            }
        }

        #endregion
    }
}
